import { store } from '/@/store/index';
import axios from 'axios';
import { ElLoading, ElNotification } from 'element-plus';

let loading:{close():void};
// 创建 axios 实例
const request = axios.create({
    // API 请求的默认前缀
    baseURL: import.meta.env.VITE_BASE_API as string | undefined,
    // 当发送跨域请求时携带cookie
    // withCredentials: true,
    timeout: 5000 // 请求超时时间
});

// 异常拦截处理器
const errorHandler = (error:{message:string}) => {
    loading.close();
    console.log(`err${error}`);
    ElNotification({
        title: '请求失败',
        message: error.message,
        type: 'error'
    });
    return Promise.reject(error);
};

// request interceptor
request.interceptors.request.use(config => {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.4)'
    });
    const token = store.state.layout.token.ACCESS_TOKEN;
    // 如果 token 存在
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    if (token) {
        config.headers['Access-Token'] = token;
    }
    return config;
}, errorHandler);

// response interceptor
request.interceptors.response.use((response) => {
    const res = response.data;
    loading.close();
    // 如果状态码不是20000则认为有错误
    if(res.code !== 20000) {
        let title = '请求失败';
        // 50008: 非法令牌; 50012: 其他客户端已登入; 50014: 令牌过期;
        if(res.code === 50008 || res.code === 50012 || res.code === 50014) {
            if (store.state.layout.token.ACCESS_TOKEN) {
                store.commit('layout/logout');
            }
            title = '身份认证失败';
        }
        ElNotification({
            title,
            message: res.message,
            type: 'error'
        });
        return Promise.reject(new Error(res.message || 'Error'));
    }
    return response;
}, errorHandler);

export default request;